package com.duff.download.okdownload.database.operator;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

public class Condition<T extends Condition> {

    protected StringBuilder mConditionBuilder = new StringBuilder();

    protected List<String> mWhereArgs = new ArrayList<String>();

    public T and() {
        mConditionBuilder.append(" AND ");
        return (T)this;
    }

    public T or() {
        mConditionBuilder.append(" OR ");
        return (T)this;
    }

    public Condition() {
    }

    public String getConditionString() {
        return mConditionBuilder.toString();
    }

    public String[] getConditionArgs() {
        String[] args = new String[mWhereArgs.size()];
        mWhereArgs.toArray(args);
        return args;
    }

    List<String> getWhereArgsList() {
        return mWhereArgs;
    }

    public T add(String column, Operator operator, int value) {
        return addConditionInner(column, operator, value);
    }

    public T add(String column, Operator operator, long value) {
        return addConditionInner(column, operator, value);
    }

    public T add(String column, Operator operator, String value) {
        return addConditionInner(column, operator, value);
    }

    public T add(String column, Operator operator, String[] value) {
        return addConditionInner(column, operator, value);
    }

    public T add(String column, Operator operator, List<String> value) {
        return addConditionInner(column, operator, value);
    }

    protected T addConditionInner(String column, Operator operator, Object value) {
        if (TextUtils.isEmpty(column) || operator == null) {
            return (T)this;
        }

        //add condition
        mConditionBuilder.append(column);
        mConditionBuilder.append(operator.toString());

        //add args
        addWhereArgs(value);

        return (T)this;
    }

    protected void addWhereArgs(Object value) {
        if (value instanceof Integer || value instanceof Long) {
            mWhereArgs.add(String.valueOf(value));
        } else if (value instanceof Boolean) {
            mWhereArgs.add((Boolean)value ? "1" : "0");
        } else if (value instanceof String) {
            mWhereArgs.add((String)value);
        } else if (value instanceof String[]) {
            String[] ss = (String[])value;
            for (String s : ss) {
                mWhereArgs.add(s);
            }
        } else if (value instanceof List) {
            List<String> valueArray = (List<String>)value;
            for (String item : valueArray) {
                mWhereArgs.add(item);
            }
        }else {
            mWhereArgs.add(value.toString());
        }
    }
}
